import uuid
from typing import Dict, Any
import logging
from pymilvus import connections, Collection, FieldSchema, CollectionSchema, DataType
from app.models.mysql.knowledge_file import KnowledgeFile,DatabaseManager
from app.dao.knowledge_file_dao import KnowledgeFileDAO
from app.config import settings
logger = logging.getLogger(__name__)

db_manager = DatabaseManager(settings.MYSQL_URI)
file_dao = KnowledgeFileDAO(db_manager)
class KnowledgeFileService:
    """知识文件服务类，封装知识文件相关的数据库操作"""
    def __init__(self):
        # 初始化服务
        pass
    def save_knowledge_file(self, model_param: Dict[str, Any]) -> KnowledgeFile:
        """保存新的知识文件"""
        logger.info("保存新知识文件")
        try:
            # 使用get方法简化字段赋值，设置合理默认值
            id = uuid.uuid4()
            # 转换为字符串
            model_param['id'] = str(id)
            knowledge_file = file_dao.create_file(model_param)
            logger.info(f"知识文件保存成功! ID: {knowledge_file.id}")
            return knowledge_file
        except Exception as e:
            logger.error(f"保存知识文件失败: {str(e)}", exc_info=True)
            raise
    #获取数据库的所有minio记录
    def get_all_knowledge_files(self):
        """获取数据库的所有minio记录"""
        logger.info("获取数据库的所有minio记录")
        try:
            files = file_dao.list_files()
            logger.info(f"获取成功")
            return files
        except Exception as e:
            logger.error(f"获取失败: {str(e)}", exc_info=True)
            raise
    #逻辑删除知识文件
    def delete_knowledge_file(self, file_id: str):
        """逻辑删除知识文件"""
        logger.info(f"开始删除知识文件: {file_id}")
        try:
            file_dao.delete_file(file_id)
            logger.info(f"删除成功: {file_id}")
        except Exception as e:
            logger.error(f"删除失败: {str(e)}", exc_info=True)
            raise

    # def add_embedding_to_milvus(self, file_id: str, embedding: list) -> bool:
    #     """
    #     新增向量到Milvus库
    #
    #     Args:
    #         file_id (str): 文件ID
    #         embedding (list): 向量数据
    #
    #     Returns:
    #         bool: 是否成功添加
    #     """
    #     try:
    #         # 连接到Milvus
    #         connections.connect(
    #             alias="test_db",
    #             host="127.0.0.1",
    #             port="19530"
    #         )
    #
    #         # 定义集合字段
    #         fields = [
    #             FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
    #             FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=len(embedding))
    #         ]
    #
    #         # 创建集合模式
    #         schema = CollectionSchema(fields, description="知识文件向量集合")
    #
    #         # 集合名称
    #         collection_name = "knowledge_file_collection"
    #
    #         # 检查集合是否存在，不存在则创建
    #         if collection_name in connections.list_collections():
    #             collection = Collection(name=collection_name)
    #         else:
    #             collection = Collection(name=collection_name, schema=schema)
    #             # 创建索引
    #             index_params = {
    #                 "index_type": "IVF_FLAT",
    #                 "metric_type": "L2",
    #                 "params": {"nlist": 128}
    #             }
    #             collection.create_index("embeddings", index_params)
    #
    #         # 准备插入数据
    #         data = [
    #             [int(file_id)],  # ID字段（假设file_id可以转换为整数）
    #             [embedding]  # 向量字段
    #         ]
    #
    #         # 插入数据
    #         collection.insert(data)
    #
    #         # 刷新确保数据持久化
    #         collection.flush()
    #
    #         logger.info(f"向量数据成功添加到Milvus，文件ID: {file_id}")
    #         return True
    #
    #     except Exception as e:
    #         logger.error(f"添加向量数据到Milvus失败: {str(e)}", exc_info=True)
    #         raise
    # # 删除milvus里的向量
    # def delete_embedding_from_milvus(self, file_id: str) -> bool:
    #     """
    #     删除向量数据从Milvus库
    #
    #     Args:
    #         file_id (str): 文件ID
    #
    #     Returns:
    #         bool: 是否成功删除
    #     """
    #     try:
    #         # 连接到Milvus
    #         connections.connect(
    #             alias="test",
    #             host="127.0.0.1",
    #             port="19530"
    #         )
    #
    #         # 集合名称
    #         collection_name = "knowledge_file_collection"
    #
    #         # 检查集合是否存在
    #         if collection_name not in connections.list_collections():
    #             logger.warning(f"集合 {collection_name} 不存在")
    #             return False
    #
    #         # 获取集合
    #         collection = Collection(name=collection_name)
    #
    #         # 根据ID删除向量数据
    #         expr = f"id in [{file_id}]"
    #         collection.delete(expr)
    #
    #         # 刷新确保数据删除生效
    #         collection.flush()
    #
    #         logger.info(f"向量数据成功从Milvus删除，文件ID: {file_id}")
    #         return True
    #
    #     except Exception as e:
    #         logger.error(f"删除向量数据从Milvus失败: {str(e)}", exc_info=True)
    #         raise
    #修改milvus里的向量


